const app = getApp();
let util = require('../../../utils/util.js')
import * as API_Order from '../../../api/order'
import * as API_ORDER from '../../../api/order'
import { Foundation } from '../../../ui-utils/index.js'

Page({
  data: {
    order_status: {}, // 订单状态
    order_sn: '',//订单编号
    order: '',//订单信息
    skuList:'',//规格列表
    num: 0,// 计算当前订单中的商品件数
    // 倒计时
    timer: null,
    color: '#ff6f10',
    day: 0,
    hours: '00',
    minutes: '00',
    seconds: '00',
  },
  onLoad: function (options) {
    // options为页面跳转所带来的参数页面初始化 
    this.setData({order_sn: options.order_sn})
  },
  onShow: function () {
    this.setData({
      order: '',
      skuList: '',
      num: 0,
    });
    this.getOrderDetail();
  },
  // 获取订单详情
  getOrderDetail: function () {
    API_Order.getOrderDetail(this.data.order_sn).then(data => {
      let _orderStatus = {};
      this.contDown(data.cancel_left_time);
      switch (data.order_status) {
        case 'CONFIRM':
          _orderStatus = {
            status: '等待支付',
            desc: '超时未支付将自动取消，请及时支付',
            icon: 'icon-order-pay',
            color: '#e83227'
          };
          break;
        case 'PAID_OFF':
          _orderStatus = {
            status: '等待发货',
            desc: '商家正在备货，请耐心等待',
            icon: 'icon-order-wait',
            color: '#e83227'
          };
          break;
        case 'SHIPPED':
          _orderStatus = {
            status: '商家已发货',
            desc: '请留意查收包裹并及时确认收货',
            icon: 'icon-order-ship',
            color: '#0ea60c'
          };
          break;
        case 'ROG':
          _orderStatus = {
            status: '已确认收货',
            desc: '收货商品了记得给个好评哦',
            icon: 'icon-order-rog',
            color: '#0ea60c'
          };
          break;
        case 'AFTER_SERVICE':
          _orderStatus = {
            status: '售后服务中',
            desc: '正在进行退换货处理',
            icon: 'icon-order-service',
            color: '#f68812'
          };
          break;
        case 'CANCELLED':
          _orderStatus = {
            status: '订单取消了',
            desc: '好桑心，订单被取消了',
            icon: 'icon-order-cancle',
            color: '#c6c6c6'
          };
          break;
        case 'COMPLETE':
          _orderStatus = {
            status: '订单完成了',
            desc: '太棒了，订单全部完成啦',
            icon: 'icon-order-complete',
            color: '#0ea60c'
          };
          break;
        default:
          break;
      };
      data.create_time = Foundation.unixToDate(data.create_time)
      data.need_pay_money = Foundation.formatPrice(data.need_pay_money)
      data.goods_price = Foundation.formatPrice(data.goods_price)
      data.discount_price = Foundation.formatPrice(data.discount_price)
      data.shipping_price = Foundation.formatPrice(data.shipping_price)
      data.ship_time = data.ship_time ? Foundation.unixToDate(data.ship_time) : null
      data.signing_time = data.signing_time ? Foundation.unixToDate(data.signing_time) : null

      if (data.coupon_price !== 0) { data.coupon_price = Foundation.formatPrice(data.coupon_price)}
      if(data.cash_back !== 0) { data.cash_back = Foundation.formatPrice(data.cash_back)}
      if(data.gift_list){
        data.gift_list.forEach(key => {
          key.gift_price = Foundation.formatPrice(key.gift_price)
        })
      } 
      if(data.receipt_history){
        data.receipt_history.receipt_type = this.receiptType(data.receipt_history.receipt_type)
      }
      if (data.gift_coupon) { data.gift_coupon.amount = Foundation.formatPrice(data.gift_coupon.amount)} 
      const skuList = data['order_sku_list']
      if(skuList && skuList.length){
        skuList.forEach(key=>{
          key.purchase_price = Foundation.formatPrice(key.purchase_price)
          if (!key.skuName) key.skuName = this.formatterSkuSpec(key)
          if(key && key.num){
            this.setData({
              num : this.data.num += key.num
            })
          }
        })
      }
      //判断是否有操作栏
      const { allow_cancel, allow_service_cancel, allow_pay, allow_apply_service, allow_rog, allow_comment } = data.order_operate_allowable_vo;
      data.noOpera = allow_cancel || allow_service_cancel || allow_pay || allow_apply_service || data.ship_no || allow_rog || (allow_comment && data.comment_status === 'UNFINISHED') || data.comment_status === 'WAIT_CHASE';
      this.setData({
        order_status: _orderStatus,
        order: data,
        skuList: skuList
      })
    })
  },
  receiptType(type){
    switch(type){
      case 'VATORDINARY':return '增值税普通发票'
      case 'ELECTRO':return '电子普通发票'
      case 'VATOSPECIAL':return '增值税专用发票'
      default : return '不开发票'
    }
  },
  /** 规格格式化显示 */
  formatterSkuSpec(sku) {
    if (!sku.spec_list || !sku.spec_list.length) return ''
    return sku.spec_list.map(spec => spec.spec_value).join(' - ')
  },
  // 复制订单号
  orderCopy(e) {
    const orderSn = e.currentTarget.dataset.sn;
    wx.setClipboardData({
      data: orderSn,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              title: '订单号复制成功'
            });
          }
        });
      }
    });
  },
  // 显示发票弹框
  popup() { this.selectComponent('#bottomFrame').showFrame() },
  // “删除”点击效果
  deleteOrder: function () {
    let that = this;
    let orderInfo = that.data.orderInfo;

    wx.showModal({
      title: '',
      content: '确定要删除此订单？',
      success: function (res) {
        if (res.confirm) {
          util.request(api.OrderDelete, {
            orderId: orderInfo.id
          }, 'POST').then(function (res) {
            if (res.errno === 0) {
              wx.showToast({
                title: '删除订单成功'
              });
              util.redirect('/pages/ucenter/order/order');
            }
            else {
              util.showErrorToast(res.errmsg);
            }
          });
        }
      }
    });
  },  
  // “确认收货”点击效果
  rogOrder: function () {
    let that = this;
    let order_sn = that.data.order_sn;

    wx.showModal({
      title: '提示',
      content: '请确认是否收到货物，否则可能会钱财两空！',
      success: function (res) {
        if (res.confirm) {
          API_ORDER.confirmReceipt(order_sn).then(() => {
            wx.showToast({ title: '确认收货成功！' });
            this.getOrderDetail();
          });
        }
      }
    });
  },
  /** 倒计时 */
  contDown(time){
    let times = time
    this.setData({
      timer:setInterval(()=>{
        if (times <= 0) {
          clearInterval(this.data.timer);
          this.triggerEvent('count-end');
        } else {
          const endTime = Foundation.countTimeDown(times);
          this.setData({
            day: endTime.day,
            hours: endTime.hours,
            minutes: endTime.minutes,
            seconds: endTime.seconds
          })
          times --
        }
      },1000)
    })
  }
})